package cn.brilliantfuture.commentry.servlet;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;

/**
 * 
 * Title: Communication Entry
 * 
 * Author:  LiTian  
 *
 * Date: 2012-4-17
 * 
 * Description:
 * 
 */
public abstract class AbstractHttpServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	protected static Logger logger = Logger.getLogger(AbstractHttpServlet.class);

	public static final String JSON_DATA_FORMAT = "json";

	public static final String XML_DATA_FORMAT = "xml";

	/**
	 * 参数调用错误
	 */
	public static final String PARAM_ERROR = "PARAM_ERROR";

	/**
	 * 数据格式错误
	 */
	public static final String DATA_FORMAT_ERROR = "DATA_FORMAT_ERROR";

	/**
	 * 调用失败
	 */
	public static final String INVOKE_FAILURE = "INVOKE_FAILURE";

	/**
	 * 调用成功
	 */
	public static final String INVOKE_SUCCESS = "INVOKE_SUCCESS";

	/**
	 * 根据条件没有找到相关数据
	 */
	public static final String NULL_DATA = "NULL_DATA";

	/**
	 * 支付成功
	 */
	public static final String PAYMENT_SUCCESS = "PAYMENT_SUCCESS";

	/**
	 * 支付失败
	 */
	public static final String PAYMENT_FAILURE = "PAYMENT_FAILURE";
	
	/**
	 * 余额不足
	 */
	public static final String SCANT_BALANCE = "SCANT_BALANCE";
	
	/**
	 * 重复提交
	 */
	public static final String DUPLICATE_SUBMIT = "DUPLICATE_SUBMIT";
	
	protected InitialContext context;
	
	public AbstractHttpServlet() {
		init();
	}

	/**
	 * 相关参数验证
	 * 
	 * @param appKey
	 *            为其分配的KEY
	 * @param appCode
	 *            为其分配的CODE
	 * @param version
	 *            当前协议版本
	 * @param timestamp
	 *            时间戳
	 * @param format
	 *            数据格式
	 * @return boolean
	 */
	protected boolean validParam(String appKey, String appCode, String version, String timestamp, String format) {
		
		logger.info("appKey -> " + appKey + " appCode -> " + appCode + " version -> " + version + " timestamp -> " + timestamp + " format -> " + format);
		
		boolean isApp = false;
		boolean isVersion = true;
		boolean isTimestamp = true;
		boolean isFormat = false;

		if (null != appKey && null != appCode)
			isApp = true;
		else
			isApp = false;

		if (null != format)
			if (!format.equals(JSON_DATA_FORMAT) && !format.equals(XML_DATA_FORMAT))
				isFormat = false;
			else
				isFormat = true;
		else
			isFormat = true;

		if (isApp && isVersion && isTimestamp && isFormat)
			return true;
		else
			return false;
	}

	/**
	 * 初始化访问环境
	 */
	public void init() {
		Properties properties = new Properties();
		properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		properties.put(Context.PROVIDER_URL, "localhost:1099");
		properties.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
		
		try {
			context = new InitialContext(properties);
		} catch (NamingException e) {
			logger.error(e);
		}
	}

}
